#include "hal_common.h"
#include "timer.h"
#include "stdio.h"
#include "hal_tim.h"
#include "led.h"
#include "multi_button.h"
/**
 * TIM6 通用定时器，用于LED灯的闪烁
 * 100ms间隔闪烁一次，即100ms定时器中断一次
 * 假设TIM6 预分频prescaler = 1200-1，即120000000/1200 = 100K的计数频率，
 * 在100K的计数频率下，1s中要计数100K次，100ms计数10K次，
 * 所以预装值period = 10000 - 1
 * 而mm32这里用到了 StepFreqHz = 120M/(prescaler + 1) = 120000000/1200 = 100K
*/
void BOARD_TIM6_Init(void)
{
    uint32_t prioritygroup = 0;
    /* Set the counter counting step. */
    TIM_Init_Type tim_init;
    tim_init.ClockFreqHz = 120000000;
    tim_init.StepFreqHz = 100000; /* 100ms. */
    tim_init.Period = 10000-1;
    tim_init.EnablePreloadPeriod = false;
    tim_init.PeriodMode = TIM_PeriodMode_Continuous;
    tim_init.CountMode = TIM_CountMode_Increasing;
    TIM_Init(TIM6, &tim_init);

    // prioritygroup = NVIC_GetPriorityGrouping();
    // NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(prioritygroup, 0, 1));
    /* Enable interrupt. */
    NVIC_EnableIRQ(TIM6_IRQn);
    TIM_EnableInterrupts(TIM6, TIM_INT_UPDATE_PERIOD, true);

    /* Start the counter. */
    TIM_Start(TIM6);
}

/* TIM_BASIC Period timeout ISR. */
void TIM6_IRQHandler(void)
{
    uint32_t flags = TIM_GetInterruptStatus(TIM6);
    if ( 0u != (flags & TIM_STATUS_UPDATE_PERIOD ) ) /* Check update status. */
    {
        LED_Toggle();
    }
    TIM_ClearInterruptStatus(TIM6, flags);
}

/**
 * TIM7 通用定时器，Mutilbutton 处理数据
 * 5ms中断一次，调用 button_ticks
 * 假设TIM6 预分频prescaler = 1200-1，即120000000/1200 = 100K的计数频率，
 * 在100K的计数频率下，1s中要计数100K次，5ms计数500次，
 * 所以预装值period = 500 - 1
 * 而mm32这里用到了 StepFreqHz = 120M/(prescaler + 1) = 120000000/1200 = 100K
*/
void BOARD_TIM7_Init(void)
{
    uint32_t prioritygroup = 0;
    /* Set the counter counting step. */
    TIM_Init_Type tim_init;
    tim_init.ClockFreqHz = 120000000;
    tim_init.StepFreqHz = 100000; /* 5ms. */
    tim_init.Period = 500-1;
    tim_init.EnablePreloadPeriod = false;
    tim_init.PeriodMode = TIM_PeriodMode_Continuous;
    tim_init.CountMode = TIM_CountMode_Increasing;
    TIM_Init(TIM7, &tim_init);

    // prioritygroup = NVIC_GetPriorityGrouping();
    // NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(prioritygroup, 0, 1));
    /* Enable interrupt. */
    NVIC_EnableIRQ(TIM7_IRQn);
    TIM_EnableInterrupts(TIM7, TIM_INT_UPDATE_PERIOD, true);

    /* Start the counter. */
    TIM_Start(TIM7);
}

/* TIM_BASIC Period timeout ISR. */
void TIM7_IRQHandler(void)
{
    uint32_t flags = TIM_GetInterruptStatus(TIM7);
    if ( 0u != (flags & TIM_STATUS_UPDATE_PERIOD ) ) /* Check update status. */
    {
        button_ticks();
    }
    TIM_ClearInterruptStatus(TIM7, flags);
}